layui.use(['table', 'form'], function () {
    const table = layui.table,
        form = layui.form;

    // 创建渲染实例
    table.render({
        elem: '#ID-material-list',
        url: URL_SYSTEM_MATERIAL,
        toolbar: '#ID-material-list-toolbar',
        defaultToolbar: ['filter', 'exports'],
        height: 'full-85',
        cellMinWidth: 80,
        page: true,
        cols: [[
            {type: 'checkbox', fixed: 'left'},
            {field: 'materialCode', title: '材料编码', width: 220},
            {field: 'materialName', title: '材料名称', width: 280, sort: true},
            {field: 'materialPrice', title: '材料价格', width: 120, sort: true},
            {field: 'materialNum', title: '库存数量', width: 120, sort: true},
            {field: 'materialDesc', title: '材料描述'},
            {fixed: 'right', title: '操作', width: 134, minWidth: 125, toolbar: '#ID-material-list-bar'}
        ]],
        error: function (res, msg) {
            console.log(res, msg)
        }
    });

    // 触发表格复选框选择
    table.on('checkbox(material-list)', function (obj) {
        let materialCode = obj?.data?.materialCode;
        let dataStr = layui.sessionData(CACHE_MATERIAL_TABLE)[CACHE_MATERIAL_CHECKED_KEY];
        let materialList = [];
        if (!isEmpty(dataStr)) {
            materialList = JSON.parse(dataStr);
        }
        // 判断是选中还是取消
        if (obj.checked) {
            materialList.push(obj?.data);
        } else {
            materialList = materialList.filter(item => item.materialCode !== materialCode);
        }
        layui.sessionData(CACHE_MATERIAL_TABLE, {
            key: CACHE_MATERIAL_CHECKED_KEY,
            value: JSON.stringify(materialList)
        });
    });

    // 触发表格单选框选择
    table.on('radio(material-list)', function (obj) {
        console.log(obj)
    });

    // 触发单元格工具事件
    table.on('tool(material-list)', function (obj) {
        const data = obj.data;
        if (obj.event === 'edit') {
            layer.open({
                id: 'layer-material',
                type: 2,
                area: ['100%', '100%'],
                title: '编辑 - id:' + data.materialCode,
                content: 'material-edit.html',
                success: function (layero, index) {
                    let body = layer.getChildFrame('body', index);
                    body.find('#code').val(data.materialCode);
                }
            });
        }
        if (obj.event === 'delete') {
            layer.confirm('确定删除' + data.materialCode + '吗?', {icon: 3, title: '警告'}, function (index) {
                layer.close(index);
            });
        }
    });

    form.on('submit(material-list-search)', function(data){
        let materialCode = data.field.materialCode;
        let materialName = data.field.materialName;
        table.reload(TABLE_ID_MATERIAL, {
            url: URL_SYSTEM_MATERIAL + '?materialCode=' + materialCode + '&materialName=' + materialName
        });
        return false;
    });
});